package com.starblink.store

import android.content.Context
import com.starblink.android.basic.aroute.CommonRoute
import com.starblink.android.basic.ext.visible
import com.starblink.android.basic.extension.navigationTo
import com.starblink.android.basic.sensorsdata.extension.trackData
import com.starblink.android.basic.sensorsdata.spm.cfg.SpmElementDef
import com.starblink.android.basic.sensorsdata.spm.cfg.SpmPageDef
import com.starblink.android.basic.user.UserDataCenter
import com.starblink.android.basic.util.post.CommonMutateManage
import com.starblink.basic.apollo.ext.ApolloValSetExt.apolloValue
import com.starblink.basic.route.RoutePage
import com.starblink.basic.style.R
import com.starblink.basic.util.CommUtils
import com.starblink.rocketreserver.fragment.MerchantWebVOF
import com.starblink.rocketreserver.fragment.ProductF
import com.starblink.store.databinding.LayoutStoreDetailBasicInfoBinding
import kotlinx.coroutines.*

/**
 * 店铺管理器
 */
object StoreManager {
    const val KEY_THIRD_LOGIN_ACCOUNT = "KEY_THIRD_LOGIN_ACCOUNT"
    const val KEY_EMAIL = "KEY_EMAIL"
    const val KEY_USERNAME = "KEY_USERNAME"
    const val KEY_PERSONAL_PROFILE = "KEY_PERSONAL_PROFILE"

    /**
     * 三方登录类型
     * 10-facebook一键登录, 11-Google一键登录, 12-Apple一键登录
     */
    const val THIRD_LOGIN_GOOGLE = 11
    const val THIRD_LOGIN_FACEBOOK = 10

    /**
     * 跳转店铺Web页面
     */
    fun navigationToStoreWebPage(merchant: MerchantWebVOF) {
        navigationTo(RoutePage.Store.PAGE_LINK) {
            withString(RoutePage.Store.STORE_ID, merchant.id)
            withString(RoutePage.Store.URL, merchant.merchantWebUrl)
            withString(RoutePage.Store.STORE_LOGO, merchant.logo)
            withString(RoutePage.Store.STORE_NAME, merchant.merchantName)
            withBoolean(RoutePage.Store.SUB_OR_NOT, merchant.subOrNot)
        }
    }

    /**
     * 跳转到商品web页面
     */
    fun navigationToProductWebPage(activity: Context, product: ProductF) {
        if (product.valid == true) {
            product.id?.let { it1 ->
                product.merchantWeb?.let { it2 ->
                    CommonRoute.startProductLink(
                        activity = activity,
                        webUrl = product.url,
                        id = it1,
                        productId = product.productId ?: "",
                        standardSpuIds = product.standardSpuIds ?: "",
                        collect = product.collected == true,
                        type = product.type,
                        storeId = it2.id,
                        storeName = it2.merchantName ?: "",
                        storeLogo = it2.logo,
                        storeFollow = it2.subOrNot,
                        affInfoLink = product.affInfo?.link,
                        traceId = product.traceId ?: ""
                    )
                }
            }
        }
    }

    /**
     * 设置店铺信息视图订阅状态
     */
    fun refreshFollowData(
        store: MerchantWebVOF,
        layoutStoreDetailBasicInfoBinding: LayoutStoreDetailBasicInfoBinding,
    ) {
        var subOrNot = !store.subOrNot
        store.apolloValue("subOrNot", subOrNot)
        val subNum =
            if (store.subOrNot) store.subNum + 1 else store.subNum - 1
        store.apolloValue("subNum", subNum)
        setFollowState(subOrNot, subNum, layoutStoreDetailBasicInfoBinding)
    }

    /**
     * 设置店铺信息视图订阅状态
     */
    fun setFollowState(
        subOrNot: Boolean,
        subNum: Int,
        layoutStoreDetailBasicInfoBinding: LayoutStoreDetailBasicInfoBinding,
    ) {
        if (subOrNot) {
            layoutStoreDetailBasicInfoBinding.vFollow.setImageResource(com.starblink.library.widget.R.mipmap.ic_brand_detail_following)
        } else {
            layoutStoreDetailBasicInfoBinding.vFollow.setImageResource(com.starblink.library.widget.R.mipmap.ic_brand_detail_follow)
        }
        layoutStoreDetailBasicInfoBinding.tvSubscribers.text =
            "$subNum Followers"
    }

    /**
     * 关注或取消关注店铺
     * 如果店铺未关注，则关注店铺。关注成功，显示成功弹窗；未登录关注10个以上，显示错误弹窗
     * 如果店铺已关注，则取消关注店铺。先显示确认弹窗。
     */
    fun followStore(
        merchant: MerchantWebVOF,
        activity: Context,
        coroutineScope: CoroutineScope,
        viewBinding: LayoutStoreDetailBasicInfoBinding,
    ) {
        CommonMutateManage.subscribeOrNotMerchant(
            activity,
            merchantId = merchant.id,
            merchantName = merchant.merchantName ?: "",
            subOrNot = merchant.subOrNot,
            scope = coroutineScope,
            merchant = merchant,
            resultCallback = { state ->
                if (state) {
                    refreshFollowData(merchant, viewBinding)
                    viewBinding.root.trackData(
                        page = SpmPageDef.StoreDetailPage,
                        element = SpmElementDef.HomeNewSubStoreSmallAdd,
                        onlyHit = true,
                        params = mapOf(
                            "merchantName" to "${merchant.merchantName}",
                            "status" to (if (UserDataCenter.isLogin()) "1" else "0"),
                            "result" to "${if (merchant?.subOrNot == true) "0" else "1"}"
                        )
                    )
                }
            }
        )
    }

    /**
     * 显示店铺文本图标（店铺名首字母）
     */
    fun showStoreTextIcon(
        merchant: MerchantWebVOF,
        viewBinding: LayoutStoreDetailBasicInfoBinding,
    ) {
        viewBinding.tvStoreIcon.visible()
        viewBinding.tvStoreIcon.text =
            merchant.merchantName?.first().toString().uppercase()
    }
}